const { studentsModel } = require('../models/stuentsModel');

module.exports.createStudents = async function (req, res, next) {
   //  接收前端发送的数据
   // console.log('新增的学生结果', result);
   try {
      const data = req.body;

      let result = await studentsModel.create(data);
      // let result1 = await studentsModel.delete(data);

      if (result) {

         res.send({
            massage: "学生数据新增成功",
            code: 1,
            result
         })
      }
      // else if(result1){
      //    res.send({
      //       massage: "学生数据删除成功",
      //       code: 1,
      //       result1
      //    })
      // }
   } catch (error) {
      console.log('垃圾服务器');
      res.send({
         massage: "学生数据新增失败",
         code: 0,
         result
      })
   }

}
// 删除学生数据
module.exports.deleteStudents = async function (req, res, next) {
   //  接收前端发送的数据
   let data = req.body;
   console.log(data);
   console.log(data._id);
   let result = await studentsModel.deleteOne({ _id: data._id });
   res.send({
      massage: "学生数据删除成功",
      code: 1,
      result
   })
}


module.exports.getStudents = async function (req, res) {
   const {pageSize , currentPage ,type = 'name',value ='' } = req.query
   const total = await studentsModel.countDocuments( {[type]: { $regex: value, $options: '$i' }}) //数据总数
   let pages = 1;
   if (pageSize) {

      pages = Math.ceil(total / pageSize)
   }
   let result = await studentsModel
      .find({[type]: { $regex: value, $options: '$i' }})
      .populate('subjectsId classesId')
      .limit(pageSize - 0)
      .skip((currentPage - 1) * pageSize)

   console.log(result);
   res.send({
      massage: '学生数据获取成功',
      code: 1,
      result:{
         total,pages,rows:result
      }
   })
}

module.exports.updateStudents = async function (req, res) {
   let data = req.body;
   const result = await studentsModel.find(data);
   if (result.length > 0) {
      res.send({
         massage: '学生数据获取成功',
         code: 1,
         result
      })
   } else {
      res.send({
         massage: '根据_id获取学生数据失败',
         code: 0,
      })
   }



}